package com.wxy.favorites.controller;

import cn.hutool.http.ContentType;
import com.wxy.favorites.dto.ShareFileDto;
import com.wxy.favorites.service.UserFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * <p>
 * 下载分享资源
 * </p>
 *Ø
 * @author e-Xiaoyuan.Wang
 * @since 2023/3/6 18:16
 */
@RequestMapping("/downloadShare")
@RestController
@Api(tags = "下载分享资源")
public class DownloadShareController {

    @Autowired
    private UserFileService userFileService;

    @GetMapping("/file/{id}/{shareId}")
    @ApiOperation(value = "下载分享文件")
    public void file(HttpServletResponse response, @PathVariable Integer id, @PathVariable String shareId) throws IOException {
        ShareFileDto file = userFileService.getShareFile(id,shareId);
        response.setContentType(ContentType.OCTET_STREAM.getValue());
        response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getFilename().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        try (ServletOutputStream out = response.getOutputStream()) {
            Files.copy(file.getPath(), out);
        }
    }
}
